export default class SocketService {
  // 单例
  static instance = null
  static get Instance() {
    if (!this.instance) {
      this.instance = new SocketService()
    }
    return this.instance
  }

  // 和服务器连接的socket 对象
  ws = null

  // 连接成功的标识
  connected = false
  // 发送数据的次数
  sendRetryCount = 0
  // 重新连接的次数
  connectRetryCount = 0

  // 储存回调函数
  callBackMapping = {}
  // 定义连接服务器的方法
  connect() {
    if (!window.WebSocket) {
      return console.log('您的浏览器不支持WebSocket');
    }
    this.ws = new WebSocket('ws://localhost:9998')

    // 连接成功
    this.ws.onopen = () => {
      console.log('连接成功');
      this.connected = true
      // 连接成功后，重置重新连接的次数
      this.connectRetryCount = 0
    }
    // 连接失败
    this.ws.onclose = () => {
      console.log('连接失败');
      this.connected = false
      this.connectRetryCount++

      setTimeout(() => {
        this.connect()
      }, this.connectRetryCount * 500);

    }
    // 连接成功
    this.ws.onmessage = msg => {

      const recvData = JSON.parse(msg.data)
      console.log(recvData);
      const socketType = recvData.socketType
      if (this.callBackMapping[socketType]) {
        const action = recvData.action
        if (action === 'getData') {
          const realData = JSON.parse(recvData.data)
          this.callBackMapping[socketType].call(this, realData)
        } else if (action === 'fullScreen') {

          this.callBackMapping[socketType].call(this, recvData)

        } else if (action === 'themeChange') {
          this.callBackMapping[socketType].call(this, recvData)

        }
      }
    }
  }

  // 回调函数的注册
  registerCallBack(socketType, callBack) {
    this.callBackMapping[socketType] = callBack
  }
  // 取消某个回调函数
  unRegisterCallBack(socketType) {
    this.callBackMapping[socketType] = null
  }
  // 发送数据的方法
  send(data) {
    if (this.connected) {
      this.sendRetryCount = 0

      this.ws.send(JSON.stringify(data))

    } else {
      this.sendRetryCount++
      setTimeout(() => {
        this.send(data)
      }, this.sendRetryCount * 500);
    }
  }
}

